package com.sites.cms.site;

import java.util.Date;
import java.util.List;

import com.jfinal.aop.Inject;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.sites.cms.account.AccountService;
import com.sites.cms.permission.PermissionService;
import com.sites.cms.role.RoleService;
import com.sites.common.SiteInfo;
import com.sites.common.model.Account;
import com.sites.common.model.Permission;
import com.sites.common.model.Role;
import com.sites.common.model.Site;

/**
 * 站点管理服务层
 * 
 * @author zyg
 * 2020年2月1日 下午1:24:49
 */
public class SiteService {
	
	private Site dao = new Site().dao();
	@Inject
	private AccountService accSrv;
	@Inject
	private PermissionService permSrv;
	@Inject
	private RoleService roleSrv;

	public Ret saveSite(Site site){
		Ret ret = Ret.create();
		String siteSign = site.getSiteSign();
		Site temp = getBySiteSign(siteSign);
		if(temp != null){
			ret.setFail();
			ret.set(SiteInfo.msgKey, "站点标识不能重复！");
			return ret;
		}
		site.setCreateTime(new Date());
		site.setStatus(SiteInfo.statusDel);
		boolean flag = site.save();
		if(flag){
			ret.setOk();
			ret.set(SiteInfo.msgKey, "保存成功");
			//保存成功后需要初始化站点的基本信息，比如用户、基本权限等
			initSiteData(site);
			return ret;
		} else {
			ret.setFail();
			ret.set(SiteInfo.msgKey, SiteInfo.serverError);
			return ret;
		}
	}
	
	public Site getBySiteSign(String siteSign){
		String sql = dao.getSql("site.getBySiteSign");
		return dao.findFirst(sql, siteSign);
	}
	
	public List<Site> getAllSites(){
		String sql = dao.getSql("site.getAllSites");
		return dao.find(sql);
	}
	
	public Site getById(int id){
		return dao.findById(id);
	}
	
	public Ret updateSite(Site site){
		Ret ret = Ret.create();
		Site temp = getById(site.getId());
		temp.setSiteName(site.getSiteName());
		temp.setSiteUrl(site.getSiteUrl());
		temp.setImgMaxSize(site.getImgMaxSize());
		temp.setFileMaxSize(site.getFileMaxSize());
		temp.setVideoMaxSize(site.getVideoMaxSize());
		temp.setImgSuffix(site.getImgSuffix());
		temp.setFileSuffix(site.getFileSuffix());
		temp.setVideoSuffix(site.getVideoSuffix());
		temp.setCdsAccessLog(site.getCdsAccessLog());
		temp.setCmsAccessLog(site.getCmsAccessLog());
		temp.setSiteDes(site.getSiteDes());
		temp.setUpdateTime(new Date());
		boolean flag = temp.update();
		if(flag){
			ret.setOk();
			ret.set(SiteInfo.msgKey, "更新成功");
		} else {
			ret.setFail();
			ret.set(SiteInfo.msgKey, SiteInfo.serverError);
		}
		return ret;
	}
	
	/**
	 * 更新当前站点信息，也就是系统设置
	 * 
	 * @param site
	 * @return
	 */
	public Ret updateCurrentSite(Site site){
		Ret ret = Ret.create();
		Site temp = getById(site.getId());
		temp.setSiteName(site.getSiteName());
		temp.setSiteUrl(site.getSiteUrl());
		temp.setImgMaxSize(site.getImgMaxSize());
		temp.setFileMaxSize(site.getFileMaxSize());
		temp.setVideoMaxSize(site.getVideoMaxSize());
		temp.setImgSuffix(site.getImgSuffix());
		temp.setFileSuffix(site.getFileSuffix());
		temp.setVideoSuffix(site.getVideoSuffix());
		temp.setCdsAccessLog(site.getCdsAccessLog());
		temp.setCmsAccessLog(site.getCmsAccessLog());
		temp.setSiteDes(site.getSiteDes());
		temp.setUpdateTime(new Date());
		boolean flag = temp.update();
		if(flag){
			ret.setOk();
			ret.set(SiteInfo.msgKey, "更新成功");
			
			//数据库更新成功后初始化站点信息，起到立即生效的效果
			initSiteInfo();
		} else {
			ret.setFail();
			ret.set(SiteInfo.msgKey, SiteInfo.serverError);
		}
		return ret;
	}
	
	/**
	 * 设置主站点
	 * 
	 * @param id
	 * @return
	 */
	public Ret setMainSite(int id){
		Ret ret = Ret.create();
		String cancelMainSite = dao.getSql("site.cancelMainSite");
		Db.update(cancelMainSite);
		Site site = getById(id);
		site.setStatus(SiteInfo.statusNormal);
		boolean flag = site.update();
		if(flag){
			initSiteInfo();//初始化站点信息
			
			ret.setOk();
			ret.set(SiteInfo.msgKey, "设置成功，请访问网站首页确认");
		} else {
			ret.setFail();
			ret.set(SiteInfo.msgKey, SiteInfo.serverError);
		}
		return ret;
	}
	
	/**
	 * 初始化站点信息
	 * <br/>主要用于工程启动和站点切换时初始化站点相关的静态常量
	 */
	public void initSiteInfo(){
		//在cmsConfig.txt中的配置
		SiteInfo.uploadPath = PropKit.get("uploadPath");
		
		//在数据库中的配置
		String sql = dao.getSql("site.getMainSite");
		Site site = dao.findFirst(sql);
		if(site != null){//不为空说明数据库中设置了主站点
			SiteInfo.siteId = site.getId();
			SiteInfo.siteName = site.getSiteName();
			SiteInfo.siteSign = site.getSiteSign();
			SiteInfo.siteUrl = site.getSiteUrl();
			SiteInfo.siteDes = site.getSiteDes();
			
			SiteInfo.imgMaxSize = site.getImgMaxSize();
			SiteInfo.fileMaxSize = site.getFileMaxSize();
			SiteInfo.videoMaxSize = site.getVideoMaxSize();
			
			SiteInfo.thumbnailSuffix = site.getImgSuffix();
			//editorImgSuffix 需要做下格式转换
			SiteInfo.editorImgSuffix = formatSuffix(site.getImgSuffix());
			SiteInfo.fileSuffix = site.getFileSuffix();
			SiteInfo.videoSuffix = site.getVideoSuffix();
			//videoSuffix 需要做下格式转换
			SiteInfo.editorVideoSuffix = formatSuffix(site.getVideoSuffix());
			SiteInfo.cdsAccessLog = site.getCdsAccessLog();
			SiteInfo.cmsAccessLog = site.getCmsAccessLog();
		} else {//用于恢复默认站点
			SiteInfo.siteId = 0;
			SiteInfo.siteName = "sitesCMS";
			SiteInfo.siteSign = "_main";
			SiteInfo.siteUrl = "localhost";
			SiteInfo.siteDes = "";
			SiteInfo.imgMaxSize = 5;
			SiteInfo.fileMaxSize = 35;
			SiteInfo.videoMaxSize = 500;
			SiteInfo.fileSuffix = "txt|doc|docx|xls|xlsx|pdf|zip|rar|7z|ppt|pptx|jpg|png|gif|bmp|jpeg|mp4";
			SiteInfo.thumbnailSuffix = "jpg|png|gif|bmp|jpeg|JPG|JPEG";
			SiteInfo.editorImgSuffix = "['jpg','png','gif','bmp','jpeg','JPG','JPEG']";
			SiteInfo.videoSuffix = "mp4";
			SiteInfo.editorVideoSuffix = "['mp4']";
			SiteInfo.cdsAccessLog = "0";
			SiteInfo.cmsAccessLog = "0";
		}
		
		// 情况所有缓存，这个需要根据CacheName来清理，新增缓存后需要调整这里
		CacheKit.removeAll("accountPermCacheName");
		CacheKit.removeAll("columnsCacheName");
		CacheKit.removeAll("permCacheName");
	}
	
	/**
	 * 格式化富文本编辑器中使用的文件后缀
	 * 
	 * @param ssuffix "jpg|png|gif|bmp|jpeg|JPG|JPEG"
	 * @return "['jpg','png','gif','bmp','jpeg','JPG','JPEG']"
	 */
	private String formatSuffix(String suffix){
		String[] suffixs = suffix.split("\\|");
		String result = "";
		for(int i=0,j=suffixs.length; i<j; i++){
			result = result + "'" + suffixs[i] + "',";
		}
		result = result.substring(0, result.length() -1);
		result = "[" + result + "]";
		return result;
	}
	
	/**
	 * 初始化站点数据
	 * <br/>主要用于新增站点时从默认站点同步基础数据到数据表
	 * @param site
	 */
	public void initSiteData(Site site){
		//1.同步超级管理员用户wumoxi
		Account account = accSrv.getAdmin();
		account.setSiteId(site.getId());
		account.setCreateTime(new Date());
		account.remove("id");
		account.save();
		//2.同步权限表数据
		Permission permDao = new Permission().dao();
		String sql = permDao.getSql("permission.getAllPermission");
		List<Permission> permList = permDao.find(sql, "0");
		for(Permission p : permList){
			p.remove("id");
			p.setSiteId(site.getId());
			p.setUpdateTime(new Date());
			p.save();
		}
		//3.同步基本角色数据
		Role roleDao = new Role().dao();
		String roleSql = roleDao.getSql("role.queryAllRoles");
		List<Role> roleList = roleDao.find(roleSql, "0");
		for(Role r : roleList){
			r.remove("id");
			r.setSiteId(site.getId());
			r.setCreateTime(new Date());
			r.save();
		}
		//4.同步角色对应权限
		String rolePermSql = roleDao.getSql("role.getSiteRolePerm");
		String addRolePerm = roleDao.getSql("role.addRolePerm");
		List<Record> recordList = Db.find(rolePermSql);
		String roleName, actionKey;
		int roleId, permId;
		for(Record r : recordList){
			roleName = r.getStr("roleName");
			actionKey = r.getStr("actionKey");
			roleId = roleSrv.getByName(roleName, site.getId()).getId();
			permId = permSrv.getByActionKey(actionKey, site.getId()).getId();
			Db.update(addRolePerm, roleId, permId);
		}
	}
	
	/**
	 * 恢复默认站点
	 * @return
	 */
	public Ret resetSite(){
		Ret ret = Ret.create();
		String cancelMainSite = dao.getSql("site.cancelMainSite");
		int num = Db.update(cancelMainSite);
		if(num > 0){
			initSiteInfo();//初始化站点信息
			
			ret.setOk();
			ret.set(SiteInfo.msgKey, "设置成功，请访问网站首页确认");
		} else {
			ret.setFail();
			ret.set(SiteInfo.msgKey, SiteInfo.serverError);
		}
		return ret;
	}
}
